#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import sys, os, time
import paramiko
# from threadpool import ThreadPool,makeRequests
from concurrent.futures import ThreadPoolExecutor


def ssh_cmd(task_log_obj):
    host = task_log_obj.bind_host.host
    print(host)
    user_obj = task_log_obj.bind_host.host_user
    print(user_obj)
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
        ssh.connect(host.ip_addr, host.post, user_obj.username, user_obj.password, timeout=10)

        stdin, stdout, stderr = ssh.exec_command(task_log_obj.task.content)
        stdout_res = stdout.read()
        stderr_res = stderr.read()

        result = stdout_res + stderr_res
        print(result)
        task_log_obj.result = result
        task_log_obj.status = 0
        task_log_obj.save()
        ssh.close()
    except Exception as e:
        task_log_obj.result = e
        task_log_obj.status = 1
        task_log_obj.save()


if __name__ == '__main__':
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(base_dir)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CrazyEye.settings")
    import django

    django.setup()

    from web import models

    if len(sys.argv) == 1:
        exit("error:must provide task_id")
    task_id = sys.argv[1]
    print(task_id)
    task_obj = models.Task.objects.get(id=task_id)
    print(task_obj)

    # 1. 生成多线程
    pool = ThreadPoolExecutor(10)
    for task_log_detail_obj in task_obj.tasklogdetail_set.all():
        print(task_log_detail_obj)
        pool.submit(ssh_cmd, task_log_detail_obj)

    pool.shutdown(wait=True)
